﻿# -*- coding: utf-8 -*-

import re
import logging

from datetime import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader

from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db

from google.appengine.api import mail
from google.appengine.api import urlfetch

from xml.dom.minidom import parse, parseString

from models import Album, Picture

import methods

admin_emails = set(['appwill002@gmail.com'])

# ##################################################################################################
def render(template, payload, mimetype="text/html"):
    '''render the template with payload'''
    #return render_to_response(template, payload, mimetype=mimetype)
    t = loader.get_template(template)
    c = Context(payload)
    return HttpResponse(t.render(c), mimetype=mimetype)

def getUser(email="anonymous@gmail.com"):
    '''get all the current user, if not exist, return anonymous'''
    user = users.get_current_user()
    if not user:
        user = users.User(email)
    return user

def getLoginAndUrl(request):
    '''get toggled login and logout label and the url'''
    if users.get_current_user():
        url = users.create_logout_url(request.get_full_path())
        url_linktext = 'Logout'
    else:
        url = users.create_login_url(request.get_full_path())
        url_linktext = 'Manage'
    return url_linktext, url
    
def is_admin():
    global admin_emails
    user = users.get_current_user()
    if user and user.email():
        if user.email() in admin_emails:
            return True
    return False
    
def toUTF8(onestr):
    newstr = onestr
    try:
        newstr = unicode(newstr, 'gbk', 'ignore')
    except:
        pass
    return newstr.encode('utf-8', 'ignore')

def fs(onestr):
    return unicode(onestr, 'utf-8', 'ignore')

# ##################################################################################################
# /fetch/
def fetch(request):
    url = request.GET.get('url', None)
    if url and (url.startswith('http://') or url.startswith('https://')):
        xml_content = methods.fetchContent(url)
        if xml_content is not None:
            response = HttpResponse(xml_content)
            response['Content-Type'] = 'text/xml'
            return response

    return HttpResponse("Error!")

# ##################################################################################################
# /preview/
def preview(request):
    hl = request.GET.get('hl', 'cn')
    if hl!='cn' and hl!='en':
        hl = 'cn'
    
    url = request.GET.get('url', None)
    if url and (url.startswith('http://') or url.startswith('https://')):
        return render("preview_"+hl+".html", {'url': url})

    return HttpResponse("Error!")

# ##################################################################################################
# /cooliris/
def cooliris(request):
    url = request.GET.get('url', None)
    if url and (url.startswith('http://') or url.startswith('https://')):
        xml_content = methods.fetchContent(url)
        if xml_content is not None:
            pictures = []
            
            xml_dom = parseString(xml_content)
            pic_nodes = xml_dom.getElementsByTagName('picture')
            if pic_nodes is not None and len(pic_nodes)>0:
                for pic_node in pic_nodes:
                    title, desc, thumbnail, fullpic = getPictureMetaDataFromXMLNode(pic_node)
                    pictures.append(Picture(title=title, desc=desc, thumbnail=thumbnail, fullpic=fullpic))
            
            return render('cooliris.xml', {'pictures':pictures}, mimetype="text/xml")

    return HttpResponse("Error!")
    
def getPictureMetaDataFromXMLNode(pic_node):
    title = ''
    desc = ''
    thumbnail = ''
    fullpic = ''
    for node in pic_node.childNodes:
        if node.nodeName == 'title':
            if node.childNodes and len(node.childNodes)>0:
                title = node.childNodes[0].nodeValue
                logging.info( title )
        elif node.nodeName == 'description':
            if node.childNodes and len(node.childNodes)>0:
                desc = node.childNodes[0].nodeValue
                logging.info( desc )
        elif node.nodeName == 'thumbnail':
            if node.childNodes and len(node.childNodes)>0:
                thumbnail = node.childNodes[0].nodeValue
                logging.info( thumbnail )
        elif node.nodeName == 'fullpic':
            if node.childNodes and len(node.childNodes)>0:
                fullpic = node.childNodes[0].nodeValue
                logging.info( fullpic )
                
    return title, desc, thumbnail, fullpic
    
# ##################################################################################################
# /shares/
def shares(request):
    order = request.GET.get('order', None)
    if order is None:
        order = request.GET.get('o', None)
    
    albums = None
    if order is None:
        albums = methods.getTopEditorScoreAlbums(100)
    elif order=='time':
        albums = methods.getTopLatestAlbums(100)
    elif order=='score' or order=='rank' or order=='r' or order=='s':
        albums = methods.getTopScoreAlbums(100)
    elif order=='download' or order=='d':
        albums = methods.getTopDownloadedAlbums(100)
    elif order=='preview' or order=='click' or order=='c':
        albums = methods.getTopPreviewAlbums(100)

    return render('albums.xml', {'albums':albums}, mimetype="text/xml")

# ##################################################################################################
# /shared_with_lang/
def shared_with_lang(request, lang):
    logging.info(lang)
    if lang is None or lang.strip()=="":
        lang = 'cn'
    lang = lang.strip()
    logging.info("lang:"+lang+"|")
    
    if lang!='cn' and lang!='en':
        lang = 'cn'
    
    return HttpResponseRedirect('/?hl='+lang)
    
# ##################################################################################################
# /shared/
def shared(request):
    hl = request.GET.get('hl', 'cn')
    if hl!='cn' and hl!='en':
        hl = 'cn'
    order = request.GET.get('order', None)

    hide = 0
    user_type = "user"
    if is_admin():
        user_type = "admin"
        hide = 1
    
    albums = None
    template_file = 'albums.html'
    
    if order is None:
        albums = methods.getTopEditorScoreAlbums(100, hide)
        template_file = 'albums_index_' + hl + '.html'
    elif order=='time':
        albums = methods.getTopLatestAlbums(100, hide)
    elif order=='score':
        albums = methods.getTopScoreAlbums(100, hide)
    elif order=='download':
        albums = methods.getTopDownloadedAlbums(100, hide)
    elif order=='preview':
        albums = methods.getTopPreviewAlbums(100, hide)
    
    count = len(albums)
    height = (count/5+1)*257
    if count%5==0:
        height = (count/5)*257
    
    max_editor_score = methods.getMaxAlbumEditorScore()
    min_editor_score = methods.getMinAlbumEditorScore()
    
    url_linktext, url = getLoginAndUrl(request)
    
    return render(template_file, {'albums':albums, 'div_height': str(height), 'user_type': user_type, 'min_editor_score': str(min_editor_score), 'max_editor_score': str(max_editor_score), 'admin_text': url_linktext, 'admin_url': url, 'hl':hl})

# ##################################################################################################
# /(?P<shareid>\d+)/
def albumxml(request, shareid):
    if shareid is None:
        return HttpResponse("")

    logging.info(shareid)
    album = methods.getAlbumById(int(shareid))
    if album:
        album.download_count = album.download_count + 1
        if album.download_count > album.preview_count:
            album.iphone_download_count = album.download_count - album.preview_count
        else:
            album.iphone_download_count = 0;
        album.put()

        response = HttpResponse(album.xml)
        response['Content-Type'] = 'text/xml'
        return response
    else:
        return HttpResponse("")

# ##################################################################################################
# /thumbup/(?P<shareid>\d+)/
def thumbup(request, user_type, shareid):
    logging.info(user_type)
    logging.info(shareid)
    
    score = 0
    album = methods.getAlbumById(int(shareid))
    if album:
        if user_type == 'user':
            album.support_score = album.support_score + 1
            album.put()
            score = album.support_score
        elif user_type == 'admin' and is_admin():
            album.editor_score = album.editor_score + 1
            album.put()
            score = album.editor_score

    response = HttpResponse(shareid+':'+str(score))
    return response

# ##################################################################################################
# /thumbdown/(?P<shareid>\d+)/
def thumbdown(request, user_type, shareid):
    logging.info(user_type)
    logging.info(shareid)
    
    score = 0
    album = methods.getAlbumById(int(shareid))
    if album:
        if user_type == 'user':
            album.support_score = album.support_score - 1
            album.put()
            score = album.support_score
        elif user_type == 'admin' and is_admin():
            album.editor_score = album.editor_score - 1
            album.put()
            score = album.editor_score

    response = HttpResponse(shareid+':'+str(score))
    return response
    
# ##################################################################################################
# /hide/(?P<shareid>\d+)/
def hide(request, shareid):
    logging.info(shareid)
    
    hide = 0
    album = methods.getAlbumById(int(shareid))
    if album:
        if is_admin():
            album.hide = 1 - album.hide
            album.put()
            hide = album.hide

    response = HttpResponse(shareid+':'+str(hide))
    return response
    
# ##################################################################################################
# /delete/(?P<shareid>\d+)/
def delete(request, shareid):
    logging.info(shareid)
    
    success = 0
    album = methods.getAlbumById(int(shareid))
    if album:
        if is_admin():
            album.delete()
            success = 1

    response = HttpResponse(shareid+':'+str(success))
    return response

# ##################################################################################################
# /albumpreview/(?P<shareid>\d+)/
def albumpreview(request, shareid):
    preview_count = 0
    album = methods.getAlbumById(int(shareid))
    if album:
        album.preview_count = album.preview_count + 1
        if album.download_count > album.preview_count:
            album.iphone_download_count = album.download_count - album.preview_count
        else:
            album.iphone_download_count = 0;
        album.put()
        score = album.preview_count

    response = HttpResponse(shareid+':'+str(preview_count))
    return response

# ##################################################################################################
# /picasa/
def picasa(request):
    hl = request.GET.get('hl', 'cn')
    if hl!='cn' and hl!='en':
        hl = 'cn'
    
    url = request.POST.get('url', None)
    if url is None or url.strip()=='':
        return render("picasa_"+hl+".html", {'hl':hl})

    album = methods.addAlbumFromURL(url)
    
    if album is None:
        return render("picasa_"+hl+".html", {'hl':hl})

    return HttpResponseRedirect('/')


# ##################################################################################################